package me.roger.zen.utils;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

import me.roger.zen.application.ZenApplication;
import me.roger.zen.model.ZenLoginModel;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.view.Display;
import android.view.WindowManager;

public class ZenUtils {

	public static boolean night;
	public static final String ZEN_READ_MODE_CHANGE = "zen.read_mode_change";
	private static final int ZEN_IMAGE_WIDTH = 480;
	private static final String ZEN_READ_MODE = "zen_read_mode";
	private static final String ZEN_NIGHT_MODE = "zen_night_mode";
	
	public static void initReadMode() {
		Context context = ZenApplication.getAppContext();
		SharedPreferences preference = context.getSharedPreferences(ZEN_READ_MODE, 0);
		night = preference.getBoolean(ZEN_NIGHT_MODE, false);
	}
	
	public static void changeReadMode(Activity activity) {
		if (activity == null) {
			System.out.println("changeReadMode: activity is null");
			return;
		}
		// change night mode flag
		night = !night;
		
		// save config
		SharedPreferences preference = activity.getSharedPreferences(ZEN_READ_MODE, 0);
		Editor editor = preference.edit();
		editor.putBoolean(ZEN_NIGHT_MODE, night);
		editor.commit();
		
		// change mode
		Intent intent = activity.getIntent();
		activity.overridePendingTransition(0, 0);
		intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
		activity.finish();
		activity.overridePendingTransition(0, 0);
		activity.startActivity(intent);		
	}
	
	public static String md5(String string) {
		byte[] hash;
		try {
			hash = MessageDigest.getInstance("MD5").digest(
					string.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("Huh, MD5 should be supported?", e);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("Huh, UTF-8 should be supported?", e);
		}

		StringBuilder hex = new StringBuilder(hash.length * 2);
		for (byte b : hash) {
			if ((b & 0xFF) < 0x10)
				hex.append("0");
			hex.append(Integer.toHexString(b & 0xFF));
		}
		return hex.toString();
	}

	public static String getToken() {
		ZenLoginModel model = ZenLoginModel.getInstance();
		if (model.isLogedin) {
			return model.userInfo.token;
		}
		return null;
	}

	public static String getUid() {
		ZenLoginModel model = ZenLoginModel.getInstance();
		if (model.isLogedin) {
			return model.userInfo.uid;
		}
		return null;
	}

	public static String getMsgToken() {
		ZenLoginModel model = ZenLoginModel.getInstance();
		if (model.isLogedin) {
			return model.userInfo.msgToken;
		}
		return null;
	}

	public static String timestamp() {
		Date date = new Date();
		long time = date.getTime();
		return "" + time;
	}

	public static InputStream resizeImage(String path, String name) {
		try {
			Context context = ZenApplication.getAppContext();
			Bitmap bm = decodeImage(path);
			if (bm != null) {
				OutputStream out = context.openFileOutput(name,
						Context.MODE_PRIVATE);
				bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
				out.close();
				InputStream input = context.openFileInput(name);
				return input;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@SuppressLint("NewApi")
	@SuppressWarnings("deprecation")
	public static int screenWidth() {
		Context context = ZenApplication.getAppContext();
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();
		int width = 0;
		int sdk = android.os.Build.VERSION.SDK_INT;
		if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB_MR2) { // Level 13
			width = display.getWidth();

		} else {
			Point size = new Point();
			display.getSize(size);
			width = size.x;
		}

		return width;
	}

	@SuppressLint("NewApi")
	@SuppressWarnings("deprecation")
	public static int width() {
		Context context = ZenApplication.getAppContext();
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();
		int width = 0;
		int sdk = android.os.Build.VERSION.SDK_INT;
		if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB_MR2) { // Level 13
			width = display.getWidth();

		} else {
			Point size = new Point();
			display.getSize(size);
			width = size.x;
		}

		if (width - 40 > ZEN_IMAGE_WIDTH) {
			width = width - 40;
		}

		return width;
	}

	@SuppressLint("NewApi")
	@SuppressWarnings("deprecation")
	public static int maxWidth(int outWidth, int outHeight) {
		// OpenGL support 2048 x 2048
		int maxWidth = outWidth;
		int maxHeight = outHeight;

		while (maxWidth > 2048 || maxHeight > 2048) {
			maxWidth = (int) (maxWidth * 0.9f);
			maxHeight = (int) (maxHeight * 0.9f);
		}

		Context context = ZenApplication.getAppContext();
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();
		int width = 0;
		int sdk = android.os.Build.VERSION.SDK_INT;
		if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB_MR2) { // Level 13
			width = display.getWidth();

		} else {
			Point size = new Point();
			display.getSize(size);
			width = size.x;
		}

		if (width - 40 > ZEN_IMAGE_WIDTH) {
			width = width - 40;
		}
		if (width > maxWidth) {
			width = maxWidth;
		}
		return width;
	}

	public static Bitmap decodeImage(String path) {
		try {

			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(path, options);
			options.inJustDecodeBounds = false;
			int be = (int) (options.outWidth / (float) maxWidth(
					options.outWidth, options.outHeight));

			if (be <= 0) {
				be = 1;
			}
			options.inPreferredConfig = Bitmap.Config.RGB_565;
			options.inSampleSize = be;
			Bitmap bitmap = BitmapFactory.decodeFile(path, options);
			return bitmap;
		} catch (OutOfMemoryError error) {
			error.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Bitmap decodeInputStream(InputStream is) {
		try {
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(is, null, options);
			options.inJustDecodeBounds = false;
			int be = (int) (options.outWidth / (float) ZEN_IMAGE_WIDTH);

			if (be <= 0) {
				be = 1;
			}

			options.inSampleSize = be;
			Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
			return bitmap;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Bitmap decodeByteArray(byte[] data) {
		try {
			if (data == null) {
				return null;
			}
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeByteArray(data, 0, data.length, options);
			options.inJustDecodeBounds = false;
			int be = (int) (options.outWidth / (float) ZEN_IMAGE_WIDTH);

			if (be <= 0) {
				be = 1;
			}

			options.inSampleSize = be;
			Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
					options);
			return bitmap;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String sub(String begin, String end, String src)
			throws Exception {
		int indexBegin = src.indexOf(begin);
		if (indexBegin != -1) {
			String sub = src.substring(indexBegin + begin.length());
			if (end == null) {
				return sub;
			}
			int indexEnd = sub.indexOf(end);
			if (indexEnd != -1) {
				return sub.substring(0, indexEnd);
			}
		}
		return null;
	}

	public static String rootDir() {
		File root = android.os.Environment.getExternalStorageDirectory();
		File dir = new File(root.getAbsolutePath() + "/zen");
		if (dir.exists() == false) {
			dir.mkdirs();
		}
		return dir.toString();
	}

	public static void cleanUp() {
		try {
			Context mContext = ZenApplication.getAppContext();
			File dir = mContext.getFilesDir();
			String[] list = dir.list();
			for (String fileName : list) {
				File file = new File(dir, fileName);
				if (file.isFile()) {
					file.delete();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
